package com.fcy.teamwork.business.chat

import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.fcy.teamwork.R
import com.fcy.teamwork.base.BaseActivity
import com.fcy.teamwork.base.closeKeyboard
import com.fcy.teamwork.base.log
import com.fcy.teamwork.business.SelectFromGroupDiaFragment
import com.fcy.teamwork.business.self.SelfInfoAct
import com.fcy.teamwork.databinding.ActivityChatBinding
import kotlinx.coroutines.launch

class ChatAct : BaseActivity<ActivityChatBinding>() {
    private val vm: ChatViewModel by viewModels()
    private var targetType = ""
    private val adapter = ChatMsgListAdapter().apply {
        onClickAction = { msg ->
            Intent(this@ChatAct, SelfInfoAct::class.java).apply {
                putExtra("canSenMsg", false)
                putExtra("userName", msg.fromUser.userName)
                startActivity(this)
            }
        }
    }

    private var msgPosition: Int = 0
        set(data) {
            if (data <= 0)
                return
            field = data
            binding.rvContent.scrollToPosition(field)
        }

    override fun initBinding() = ActivityChatBinding.inflate(layoutInflater)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        parseArgs()
        binding.apply {
            rvContent.also {
                it.adapter = adapter
                it.layoutManager = LinearLayoutManager(this@ChatAct)
                msgPosition = adapter.submitData(
                    vm.loadMsg().toList().apply {
                        log(this)
                    }
                )
            }
            btnSend.setOnClickListener(::onSendClick)
            actionBar.ibBack.setOnClickListener { finish() }
            actionBar.tvTitle.text = vm.loadTitle()

            root.addOnLayoutChangeListener { _, _, _, _, bottom, _, _, _, oldBottom ->
                if (oldBottom - bottom > (oldBottom / 4))
                    rvContent.scrollToPosition(msgPosition)
            }
            initObserver()
            actionBar.ibFinish.apply {
                visibility = View.VISIBLE
                setImageResource(R.drawable.ic_baseline_look_for_me_24)
                setOnClickListener {
                    if(targetType == "single"){
                        Intent(this@ChatAct, SelfInfoAct::class.java).apply {
                            putExtra("canSenMsg", false)
                            putExtra("userName", vm.targetId)
                            startActivity(this)
                        }
                    }else{
                        val fragment = SelectFromGroupDiaFragment()
                        fragment.arguments = Bundle().apply {
                            putString(SelectFromGroupDiaFragment.arguments_groupId, vm.targetId)
                            putBoolean(SelectFromGroupDiaFragment.arguments_isHideCheckBox, true)
                        }
                        fragment.show(supportFragmentManager, "")
                    }
                }
            }
        }
    }

    private fun initObserver() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                vm.dataSource.collect {
                    msgPosition = adapter.addMsg(it)
                    binding.rvContent.scrollToPosition(msgPosition)
                }
            }
        }
    }

    private fun parseArgs() {
        intent.extras?.also {
            targetType = it.getString("targetType") ?: ""
            val targetId = it.getString("targetId") ?: ""
            vm.initConversation(targetType, targetId)
        }
    }


    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_UP && currentFocus != null && shouldHide(ev)) {
            currentFocus!!.closeKeyboard()
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun shouldHide(ev: MotionEvent): Boolean {
        val leftTop = intArrayOf(0, 0)
        binding.cardInputLayout.getLocationInWindow(leftTop)
        return ev.y < leftTop[1]
    }

    private fun onSendClick(view: View) {
        val text = binding.etMsg.text.toString()
        if (text.isEmpty())
            return
        val msg = vm.sendMsg(text)
        msgPosition = adapter.addMsg(msg)
        binding.etMsg.text.clear()
    }
}